package com.autohelper.app;

import static android.content.Context.WINDOW_SERVICE;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityNodeInfo;

import io.netty.util.internal.StringUtil;

public class ActionOperator {
    private static final String TAG = "ActionOperator";
    private final AutoAccessibilityService accessibilityService;
    private static final int GESTURE_DURATION = 100;

    public ActionOperator(AutoAccessibilityService accessibilityService) {
        this.accessibilityService = accessibilityService;
    }

    // 点击指定坐标
    public boolean click(float x, float y) {
        try {
            Path path = new Path();
            path.moveTo(x, y);
            GestureDescription.Builder builder = new GestureDescription.Builder();
            builder.addStroke(new GestureDescription.StrokeDescription(path, 0, GESTURE_DURATION));
            return accessibilityService.dispatchGesture(builder.build(), null, null);
        } catch (Exception e) {
            Log.e(TAG, "点击失败: " + e.getMessage());
            return false;
        }
    }

    // 滑动操作
    public boolean swipe(int startX, int startY, int endX, int endY, long duration) {
        try {
            Path path = new Path();
            path.moveTo(startX, startY);
            path.lineTo(endX, endY);
            GestureDescription.Builder builder = new GestureDescription.Builder();
            builder.addStroke(new GestureDescription.StrokeDescription(path, 0, duration));
            return accessibilityService.dispatchGesture(builder.build(),
                    new AccessibilityService.GestureResultCallback() {
                        @Override
                        public void onCompleted(GestureDescription gestureDescription) {
                            Log.d(TAG, "滑动完成");
                        }
                    }, null);
        } catch (Exception e) {
            Log.e(TAG, "滑动失败: " + e.getMessage());
            return false;
        }
    }

    // 输入文本
    public boolean inputText(String text) {
        try {
            AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
            if (rootNode != null) {
                AccessibilityNodeInfo focusedNode = findFocusedEditText(rootNode);
                if (focusedNode != null) {
                    Bundle arguments = new Bundle();
                    arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
                    boolean result = focusedNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
                    focusedNode.recycle();
                    rootNode.recycle();
                    return result;
                }
                rootNode.recycle();
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "输入文本失败: " + e.getMessage());
            return false;
        }
    }

    // 清空文本
    public boolean clearText() {
        try {
            AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
            if (rootNode != null) {
                AccessibilityNodeInfo focusedNode = findFocusedEditText(rootNode);
                if (focusedNode != null) {
                    boolean result = focusedNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, null);
                    focusedNode.recycle();
                    rootNode.recycle();
                    return result;
                }
                rootNode.recycle();
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "清空文本失败: " + e.getMessage());
            return false;
        }
    }

    // 启动应用
    public void launchApp(String packageName, String activityName, IActionCallback callback) {
        try {
            if (StringUtil.isNullOrEmpty(activityName)) {
                Intent intent = accessibilityService.getPackageManager().getLaunchIntentForPackage(packageName);
                if (intent != null) {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    accessibilityService.startActivity(intent);
                    callback.success(true);
                } else {
                    callback.fail("启动应用失败:无法通过包名启动APP");
                }
            } else {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(packageName, activityName));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                accessibilityService.startActivity(intent);
                callback.success(true);
            }
        } catch (Exception e) {
            Log.e(TAG, "启动应用失败: " + e.getMessage());
            callback.fail("启动应用失败:" + e.getMessage());
        }
    }

    // 返回主页
    public boolean goHome() {
        return inputKey(AccessibilityService.GLOBAL_ACTION_HOME);
    }

    public boolean goBack() {
        return inputKey(AccessibilityService.GLOBAL_ACTION_BACK);
    }

    public boolean inputKey(int keycode) {
        try {
            return accessibilityService.performGlobalAction(keycode);
        } catch (Exception e) {
            Log.e(TAG, "按键操作失败: " + e.getMessage());
            return false;
        }
    }

    // 获取当前界面的XML
    public String dumpWindowHierarchy() {
        try {
            AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
            if (rootNode != null) {
                String xmlDump = dumpNodeHierarchy(rootNode, 0);
                rootNode.recycle();
                return xmlDump;
            }
            return "";
        } catch (Exception e) {
            Log.e(TAG, "获取界面层次失败: " + e.getMessage());
            return "";
        }
    }

    // 获取剪贴板内容
    public void getClipboardContent(IActionCallback callback, String appPackageName, String appActivityName) {
        try {
            ClipboardManager clipboard = (ClipboardManager) accessibilityService.getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipboard == null) {
                callback.fail("clipboard为null");
                return;
            }

            // Android 10 以下版本可以直接获取
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
                if (clipboard.hasPrimaryClip()) {
                    CharSequence text = clipboard.getPrimaryClip().getItemAt(0).getText();
                    String result = text != null ? text.toString() : "";
                    callback.success(result);
                    return;
                }
                callback.fail("clipboard.hasPrimaryClip()为false");
                return;
            }

            // 保存当前应用包名
            String currentPackage;
            String currentActivityName;
            if (StringUtil.isNullOrEmpty(appPackageName)) {
                if (accessibilityService.getRootInActiveWindow() != null) {
                    currentPackage = accessibilityService.getRootInActiveWindow().getPackageName().toString();
                    currentActivityName = "";
                } else {
                    currentPackage = "";
                    currentActivityName = "";
                }
            } else {
                currentPackage = appPackageName;
                currentActivityName = appActivityName;
            }
            Log.i(TAG, "currentPackage=" + currentPackage + " currentActivityName=" + currentActivityName);
            // 切换到最近任务
            accessibilityService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);

            // 等待最近任务界面打开
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                try {
                    // 切换到我们的应用
                    launchApp(accessibilityService.getPackageName(), MainActivity.class.getCanonicalName(), IActionCallback.NO_CALLBACK);

                    // 等待我们的应用切换到前台后获取剪贴板内容
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        try {
                            String result = "";
                            if (clipboard.hasPrimaryClip()) {
                                CharSequence text = clipboard.getPrimaryClip().getItemAt(0).getText();
                                result = text != null ? text.toString() : "";
                            }

                            // 切换回最近任务
                            accessibilityService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);

                            // 等待最近任务界面打开后切回原应用
                            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                                if (!currentPackage.isEmpty()) {
                                    launchApp(currentPackage, currentActivityName, IActionCallback.NO_CALLBACK);
                                }
                            }, 500);

                            callback.success(result);
                        } catch (Exception e) {
                            Log.e(TAG, "获取剪贴板内容失败: " + e.getMessage());
                            // 发生错误时也要切换回原应用
                            if (!currentPackage.isEmpty()) {
                                accessibilityService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);
                                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                                    launchApp(currentPackage, currentActivityName, IActionCallback.NO_CALLBACK);
                                    callback.fail(e.getMessage());
                                }, 500);
                            } else {
                                callback.fail(e.getMessage());
                            }
                        }
                    }, 500);

                } catch (Exception e) {
                    Log.e(TAG, "切换应用失败: " + e.getMessage());
                    callback.fail(e.getMessage());
                }
            }, 300);

        } catch (Exception e) {
            Log.e(TAG, "获取剪贴板内容失败: " + e.getMessage());
            callback.fail(e.getMessage());
        }
    }

    private AccessibilityNodeInfo findFocusedEditText(AccessibilityNodeInfo root) {
        if (root == null)
            return null;
        if (root.isFocused() && root.isEditable())
            return root;

        for (int i = 0; i < root.getChildCount(); i++) {
            AccessibilityNodeInfo child = root.getChild(i);
            if (child != null) {
                AccessibilityNodeInfo result = findFocusedEditText(child);
                if (result != null)
                    return result;
                child.recycle();
            }
        }
        return null;
    }

    private String dumpNodeHierarchy(AccessibilityNodeInfo node, int depth) {
        if (node == null)
            return "";

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            sb.append("  ");
        }

        Rect bounds = new Rect();
        node.getBoundsInScreen(bounds);

        sb.append(String.format(
                "<node class=\"%s\" bounds=\"%s\" text=\"%s\" content-desc=\"%s\" clickable=\"%b\" scrollable=\"%b\" editable=\"%b\">\n",
                node.getClassName(),
                bounds.toString(),
                node.getText(),
                node.getContentDescription(),
                node.isClickable(),
                node.isScrollable(),
                node.isEditable()));

        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            if (child != null) {
                sb.append(dumpNodeHierarchy(child, depth + 1));
                child.recycle();
            }
        }

        for (int i = 0; i < depth; i++) {
            sb.append("  ");
        }
        sb.append("</node>");

        return sb.toString();
    }

    public void screenCapture(IActionCallback callback) {
        ScreenCaptureService.callback = callback;
        // 创建启动服务的 Intent
        Intent serviceIntent = new Intent(this.accessibilityService, ScreenCaptureService.class);
        // 启动服务
        this.accessibilityService.startService(serviceIntent);
    }

    public int[] getWmSize() {
        // 获取窗口管理器
        WindowManager windowManager = (WindowManager) accessibilityService.getSystemService(WINDOW_SERVICE);

        // 获取屏幕的DisplayMetrics
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);

        // 获取屏幕的宽高（像素）
        int widthPixels = metrics.widthPixels;
        int heightPixels = metrics.heightPixels;
        return new int[]{widthPixels, heightPixels};
    }

    // 退出当前APP
    public boolean exitCurrentApp() {
        try {
            // 先打开最近任务视图
            boolean openRecents = accessibilityService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);
            if (!openRecents) {
                Log.e(TAG, "打开最近任务失败");
                return false;
            }

            // 等待最近任务视图打开
            Thread.sleep(500);

            // 模拟向上滑动关闭当前应用
            int[] screenSize = getWmSize();
            int screenCenterX = screenSize[0] / 2;
            int screenHeight = screenSize[1];
            return swipe(screenCenterX, screenHeight / 2, screenCenterX, 0, 300);
        } catch (Exception e) {
            Log.e(TAG, "退出应用失败: " + e.getMessage());
            return false;
        }
    }

    public interface IActionCallback {
        void success(Object data);

        void fail(String message);

        IActionCallback NO_CALLBACK = new IActionCallback() {
            @Override
            public void success(Object data) {

            }

            @Override
            public void fail(String message) {

            }
        };
    }
}